#include "HorizontalDoubleLineDrawer.h"
#include <QPen>
#include <QGraphicsScene>
#include <QGraphicsLineItem>
#include <QGraphicsSceneMouseEvent>
#include <QDebug>

// 包含MeasurementMode的定义
#include "MeasurementAlgorithmBase.h"

// 包含公共DraggableLineItem类的定义
#include "../Common/DraggableLineItem.h"

HorizontalDoubleLineDrawer::HorizontalDoubleLineDrawer(QObject *parent) 
    : QObject(parent),
      m_scene(nullptr),
      m_topLine(nullptr),
      m_bottomLine(nullptr),
      m_imageWidth(0),
      m_imageHeight(0),
      m_scale(1.0),
      m_offset(QPointF(0, 0))
{
    initializeStyles();
}

HorizontalDoubleLineDrawer::~HorizontalDoubleLineDrawer()
{
    clearAll();
}

void HorizontalDoubleLineDrawer::setScene(QGraphicsScene *scene)
{
    if (m_scene != scene) {
        // 清除之前场景中的绘制项
        clearAll();
        m_scene = scene;
        if (m_scene) {
            // 场景已设置
        }
    }
}

void HorizontalDoubleLineDrawer::initializeLine(int imageWidth, int imageHeight, double scale, const QPointF &offset)
{
    if (!m_scene) {
        qWarning() << "scenec error";
        return;
    }

    // 保存图像参数
    m_imageWidth = imageWidth;
    m_imageHeight = imageHeight;
    m_scale = scale;
    m_offset = offset;
    
    // 清除之前的绘制内容
    clearAll();
    
    // 计算默认起始和结束点 - 将线条长度设置为图像宽度
    int startX = 0;  // 从图像左侧开始
    int endX = imageWidth;  // 到图像右侧结束
    
    // 根据用户要求，将两条线分别放在图像的1/3和2/3位置
    int topY = imageHeight / 3;  // 第一条线在1/3处
    int bottomY = imageHeight * 2 / 3;  // 第二条线在2/3处
    
    // 确保线条不会超出图像高度范围
    topY = qBound(0, topY, imageHeight);
    bottomY = qBound(0, bottomY, imageHeight);
    
    // 转换为场景坐标
    QPointF topStartScene = imageToSceneCoordinates(QPointF(startX, topY));
    QPointF topEndScene = imageToSceneCoordinates(QPointF(endX, topY));
    QPointF bottomStartScene = imageToSceneCoordinates(QPointF(startX, bottomY));
    QPointF bottomEndScene = imageToSceneCoordinates(QPointF(endX, bottomY));
    
    // 创建上下线
    m_topLine = createLineItem(topStartScene, topEndScene);
    m_bottomLine = createLineItem(bottomStartScene, bottomEndScene);
    

    // 添加到场景
    addDrawingItem(m_topLine);
    addDrawingItem(m_bottomLine);
    
    // 初始触发信号
    onLinePositionChanged();
}

void HorizontalDoubleLineDrawer::clearAll()
{
    removeAllItems();
    m_topLine = nullptr;
    m_bottomLine = nullptr;
    m_drawingItems.clear();
}

MeasurementMode HorizontalDoubleLineDrawer::getMeasurementMode() const
{
    return MeasurementMode::HorizontalDoubleLine;
}

void HorizontalDoubleLineDrawer::restoreFromResult(const QVariantMap &result, double scale, const QPointF &offset)
{
    if (!m_scene || !result.contains("top_line_y") || !result.contains("bottom_line_y") ||
        !result.contains("line_left_x") || !result.contains("line_right_x")) {
        return;
    }

    // 保存图像参数
    m_scale = scale;
    m_offset = offset;
    
    // 清除之前的绘制内容
    clearAll();

    // 从结果中获取线的位置信息（图像坐标）
    qreal topY = result.value("top_line_y").toDouble();
    qreal bottomY = result.value("bottom_line_y").toDouble();
    qreal leftX = result.value("line_left_x").toDouble();
    qreal rightX = result.value("line_right_x").toDouble();
    
    // 转换为场景坐标
    QPointF topLeftScene = imageToSceneCoordinates(QPointF(leftX, topY));
    QPointF topRightScene = imageToSceneCoordinates(QPointF(rightX, topY));
    QPointF bottomLeftScene = imageToSceneCoordinates(QPointF(leftX, bottomY));
    QPointF bottomRightScene = imageToSceneCoordinates(QPointF(rightX, bottomY));

    // 重新创建线
    m_topLine = createLineItem(topLeftScene, topRightScene);
    m_bottomLine = createLineItem(bottomLeftScene, bottomRightScene);
    

    
    // 添加到场景
    addDrawingItem(m_topLine);
    addDrawingItem(m_bottomLine);
    
    // 触发位置变化信号
    onLinePositionChanged();
}

void HorizontalDoubleLineDrawer::setParameters(const QVariantMap &params)
{
    // 更新线宽
    if (params.contains("line_width")) {
        m_lineWidth = params.value("line_width").toInt();
    }

    // 更新线颜色
    if (params.contains("line_color")) {
        m_lineColor = params.value("line_color").value<QColor>();
    }


    // 重新初始化样式
    initializeStyles();

    // 更新现有绘制项的样式
    if (m_topLine) {
        m_topLine->setPen(m_linePen);
    }
    if (m_bottomLine) {
        m_bottomLine->setPen(m_linePen);
    }
}

void HorizontalDoubleLineDrawer::setScale(double scale)
{
    if (m_scale == scale && m_offset == m_offset) {
        return; // 没有变化，不需要更新
    }
    
    // 保存当前图像坐标（基于旧的缩放和偏移）
    QPointF topStartImage, topEndImage, bottomStartImage, bottomEndImage;
    bool hasLines = m_topLine != nullptr && m_bottomLine != nullptr;
    if (hasLines) {
        QLineF topLine = m_topLine->line();
        QLineF bottomLine = m_bottomLine->line();
        
        topStartImage = sceneToImageCoordinates(topLine.p1());
        topEndImage = sceneToImageCoordinates(topLine.p2());
        bottomStartImage = sceneToImageCoordinates(bottomLine.p1());
        bottomEndImage = sceneToImageCoordinates(bottomLine.p2());
    }
    
    // 更新缩放和偏移
    m_scale = scale;
    
    // 使用新的缩放和偏移将图像坐标转换回场景坐标
    if (hasLines) {
        QPointF newTopStartScene = imageToSceneCoordinates(topStartImage);
        QPointF newTopEndScene = imageToSceneCoordinates(topEndImage);
        QPointF newBottomStartScene = imageToSceneCoordinates(bottomStartImage);
        QPointF newBottomEndScene = imageToSceneCoordinates(bottomEndImage);
        
        // 更新线条位置
        m_topLine->setLine(QLineF(newTopStartScene, newTopEndScene));
        m_bottomLine->setLine(QLineF(newBottomStartScene, newBottomEndScene));
    }
}

DraggableLineItem *HorizontalDoubleLineDrawer::createLineItem(const QPointF &start, const QPointF &end)
{
    DraggableLineItem *lineItem = new DraggableLineItem(QLineF(start, end));
    lineItem->setPen(m_linePen);
    lineItem->setVertical(false); // 设置为水平线
    // 连接位置变化信号
    connect(lineItem, &DraggableLineItem::positionChanged, this, &HorizontalDoubleLineDrawer::onLinePositionChanged);
    return lineItem;
}

void HorizontalDoubleLineDrawer::onLinePositionChanged()
{ 
    // 创建结果映射，包含两条线的信息
    QVariantMap result;
    result.insert("point1", sceneToImageCoordinates(m_topLine->line().p1()));
    result.insert("point2", sceneToImageCoordinates(m_bottomLine->line().p1()));
    result.insert("measurement_mode", static_cast<int>(MeasurementMode::VerticalDoubleLine));
    
    // 发送信号，上报测量结果
    emit lineChanged(result);
}

QPointF HorizontalDoubleLineDrawer::sceneToImageCoordinates(const QPointF &scenePos) const
{
    // 场景坐标 -> 图像像素坐标
    // 图像的0,0坐标对应场景中的偏移坐标
    QPointF imagePos;
    imagePos.setX((scenePos.x() - m_offset.x()) / m_scale);
    imagePos.setY((scenePos.y() - m_offset.y()) / m_scale);
    return imagePos;
}

QPointF HorizontalDoubleLineDrawer::imageToSceneCoordinates(const QPointF &imagePos) const
{
    // 图像像素坐标 -> 场景坐标
    // 图像的0,0坐标对应场景中的偏移坐标，图像的100,100坐标等于100*m_scale + m_offset
    QPointF scenePos;
    scenePos.setX(imagePos.x() * m_scale + m_offset.x());
    scenePos.setY(imagePos.y() * m_scale + m_offset.y());
    return scenePos;
}

void HorizontalDoubleLineDrawer::initializeStyles()
{
    // 设置默认样式
    m_lineWidth = 2;
    m_lineColor = Qt::blue;

    // 初始化画笔
    m_linePen = QPen(m_lineColor, m_lineWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
}

void HorizontalDoubleLineDrawer::addDrawingItem(QGraphicsItem *item)
{
    if (m_scene && item) {
        m_scene->addItem(item);
        m_drawingItems.append(item);
    }
}

void HorizontalDoubleLineDrawer::removeAllItems()
{
    if (m_scene) {
        for (QGraphicsItem *item : qAsConst(m_drawingItems)) {
            m_scene->removeItem(item);
            delete item;
        }
    }
}
